<template>
    <a-modal :title="model.dataListId ? '修改表单列表' : '新增表单列表'" :okText="model.dataListId ? '修改' : '新增'" :width="800" visible v-if="visible" :confirmLoading="loading" @cancel="handleCancel" @ok="handleOk">
        <a-form layout="horizontal" :form="form">
            <a-form-item label="列表名称">
                <a-input v-decorator="['dataListName', { initialValue: model.dataListName, rules: [{ required: true, message: '请填写列表名称' }] }]"></a-input>
            </a-form-item>
            <a-form-item label="列表类型">
                <a-select :options="opts.type" v-decorator="['dataListType', { initialValue: model.dataListType, rules: [{ required: true, message: '请选择列表类型' }] }]"></a-select>
            </a-form-item>
            <a-form-item label="关联模型">
                <a-select :options="opts.model" v-decorator="['dataModelId', { initialValue: model.dataModelId, rules: [{ required: true, message: '请选择关联模型' }] }]"></a-select>
            </a-form-item>
            <a-form-item label="关联字段">
                <a-input v-decorator="['keyField', { initialValue: model.keyField, rules: [{ required: true, message: '请填写关联字段' }] }]"></a-input>
            </a-form-item>
            <a-form-item label="允许编辑">
                <a-select :options="opts.flag" v-decorator="['editFlag', { initialValue: model.editFlag, rules: [{ required: true, message: '请选择是否允许编辑' }] }]"></a-select>
            </a-form-item>
            <a-form-item label="字段布局">
                <a-table :columns="cols" :dataSource="opts.fields" bordered>
                    <template slot="show" slot-scope="text, record">
                        <a-switch :defaultChecked="record.show" @change="handleSwitchChange(record.name, 'show', $event)" />
                    </template>
                    <template slot="edit" slot-scope="text, record">
                        <a-switch :defaultChecked="record.edit" @change="handleSwitchChange(record.name, 'edit', $event)" />
                    </template>
                    <template slot="required" slot-scope="text, record">
                        <a-switch :defaultChecked="record.required" @change="handleSwitchChange(record.name, 'required', $event)" />
                    </template>
                    <template slot="order" slot-scope="text, record">
                        <a-input-number v-model="record.order" @change="handleOrder(record, $event)"></a-input-number>
                    </template>
                </a-table>
            </a-form-item>
            <a-form-item label="SQL语句">
                <a-textarea
                    v-decorator="[
                        'sqlStr',
                        {
                            initialValue: model.sqlStr,
                            rules: []
                        }
                    ]"
                />
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script>
import moment from 'moment';
import { create, update } from '@/api/formlist';
import { all as allForm } from '@/api/form';
import { all as allModel, getFields } from '@/api/formmodel';
import { openNotification } from '@/utils/util';

export default {
    name: 'FormListForm',
    data() {
        return {
            moment,
            form: this.$form.createForm(this, { onValuesChange: this.handleValuesChange }),
            model: {
                dataListId: null,
                dataListName: null,
                dataModelId: null,
                dataListType: 1,
                dataListLayout: '',
                ketField: null,
                editFlag: 0,
                sqlStr: null
            },
            cols: [
                {
                    title: '序号',
                    width: '80px',
                    align: 'center',
                    customRender: (text, record, index) => `${index + 1}`
                },
                {
                    title: '字段名',
                    dataIndex: 'name'
                },
                {
                    title: '字段注释',
                    dataIndex: 'comment'
                },
                {
                    title: '是否显示',
                    dataIndex: 'show',
                    scopedSlots: { customRender: 'show' }
                },
                {
                    title: '是否可编辑',
                    dataIndex: 'edit',
                    scopedSlots: { customRender: 'edit' }
                },
                {
                    title: '是否必填',
                    dataIndex: 'required',
                    scopedSlots: { customRender: 'required' }
                },
                {
                    title: '排序',
                    dataIndex: 'order',
                    scopedSlots: { customRender: 'order' }
                }
            ],
            opts: {
                form: [],
                model: [],
                fields: [],
                type: [
                    { label: '系统内标', value: 1 },
                    { label: '系统外表', value: 2 }
                ],
                flag: [
                    { label: '是', value: 1 },
                    { label: '否', value: 0 }
                ]
            },
            visible: false,
            loading: false
        };
    },
    watch: {
        'model.dataModelId': {
            immediate: true,
            handler(value, old) {
                value && this.handleLoadFields(value);
            }
        }
    },
    mounted() {
        this.handleLoadData();
    },
    methods: {
        show(row) {
            if (row) {
                this.model = {
                    ...row,
                    editFlag: row.editFlag ? 1 : 0
                };
            }
            this.visible = true;
        },
        hide() {
            this.form.resetFields();
            this.model = { formId: null, name: null, type: null, comment: null };
            this.$emit('refresh');
            this.visible = false;
        },
        handleSwitchChange(fieldName, prop, value) {
            let field = this.opts.fields.find(item => item.name === fieldName);
            field[prop] = value;
        },
        handleOrder(row, e) {
            let temp = this.opts.fields.sort((prev, next) => prev.order - next.order);
            this.$nextTick(() => {
                this.opts.fields = temp;
                temp.forEach((item, index) => {
                    item.order = index;
                });
            });
        },
        handleValuesChange(props, values) {
            let data = Object.entries(values)[0];
            this.model[data[0]] = data[1];
        },
        async handleLoadData() {
            let res = await allForm();
            if (!+res.state) {
                this.opts.form = res.data.map(item => {
                    return { ...item, value: item.dataFormId, label: item.dataFormName };
                });
            }
            res = await allModel();
            if (!+res.state) {
                this.opts.model = res.data.map(item => {
                    return { ...item, value: item.dataModelId, label: item.dataModelName };
                });
            }
        },
        async handleLoadFields(id) {
            let layout = JSON.parse(this.model.dataListLayout || '[]');
            let res = await getFields(id);
            if (!+res.state) {
                res = res.data.map((item, index) => {
                    let field = layout.find(temp => temp.name === item.name) || { show: true, edit: false, required: false, order: index };
                    field = { ...item, value: item.name, label: item.comment, order: field.order, show: !!field.show, edit: !!field.edit, required: !!field.required };
                    console.info(JSON.stringify(field));
                    return field;
                });
                this.opts.fields = res.sort((prev, next) => prev.order - next.order);
            }
        },
        handleCancel() {
            this.visible = false;
        },
        handleOk(e) {
            this.form.validateFieldsAndScroll(async err => {
                if (!err) {
                    this.loading = true;
                    this.model = Object.assign(this.model, this.form.getFieldsValue());
                    this.model.dataListLayout = JSON.stringify(this.opts.fields);
                    let save = this.model.dataListId ? update : create;
                    let res = await save(this.model);
                    if (!+res.state) {
                        openNotification('success', this.model.dataListId ? '修改表单列表成功' : '新增表单列表成功');
                        this.hide();
                    } else {
                        openNotification('error', res.message);
                    }
                    this.$emit('save');
                    this.loading = false;
                }
            });
        }
    }
};
</script>

<style lang="scss">
.ant-form {
    max-height: 50vh;
    overflow: auto;
}
</style>
